package com.tn.socket;

import com.tn.controller.alarm.common.model.weigh.vo.LedInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;


@Component
@Slf4j
public class LEDSocket {

//    public static void main(String[] args) throws IOException {
//        LEDSocket socket = new LEDSocket();
//        LedInfoVo ledInfoVo = new LedInfoVo();
//        ledInfoVo.setIp("192.168.130.69");
//        ledInfoVo.setLicense("苏A12345");
//        ledInfoVo.setMsg("允许入闸允许出闸未理货未过磅未取卡");
//        socket.ledDisplay(ledInfoVo);
//    }

    public  void ledDisplay(LedInfoVo ledInfoVo) {

        if(ledInfoVo.getIp()==null){
            return;
        }
        Socket socket = null;
        //输出流 os对象初始化
        OutputStream os = null;
        String returnMsg=null;
        try {
            //1、创建Socket对象，它的第一个参数需要的是服务端的IP，第二个参数是服务端的端口
            InetAddress inet = InetAddress.getByName(ledInfoVo.getIp());
            socket = new Socket(inet, 5000);//inet是服务端ip
            //2、获取一个输出流，用于写出要发送的数据
            os = socket.getOutputStream();
            //3、写出数据
            //第一行 车牌

            String head="A5 A5 01 ";
            String foot=" BE EF";
            if(!StringUtils.isEmpty(ledInfoVo.getLicense())){
                String s = editLicense(ledInfoVo.getLicense());
                String print16=head+s+foot;
                returnMsg=print16;
            }

            //第二行 通行结果
            if(!StringUtils.isEmpty(ledInfoVo.getMsg())){
                String s = editMsg(ledInfoVo.getMsg());
                String print16=head+s+foot;
                returnMsg=returnMsg+" "+print16;
            }
            log.debug(ledInfoVo.getIp()+"发送led屏幕报文："+returnMsg);
            os.write(hexStringToByteArray(returnMsg));
        } catch (IOException e) {
            log.error("发送报文失败："+e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
              log.error("关闭IO流失败："+e);
            }
        }

    }


    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param hexString 16进制表示的字符串
     * @return byte[] 字节数组
     */
    public  byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */
    public  String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }


    private final  String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public  String byteToHex(int n) {
        if (n < 0) {
            n = n + 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexArray[d1] + hexArray[d2];

    }

    private  String editMsg(String msg) throws UnsupportedEncodingException {
        String head = "06";
        byte[] provinceByte = msg.getBytes("gb2312");
        String s = BinaryToHexString(provinceByte);
        String[] s1 = s.split(" ");
        int length = s1.length;
        String s3 = byteToHex(length);
        s = head + " " + s3 + " " + s;
        String a = byteToHex(checkSum(s));
        s=s+a;
        String[] s2 = s.split(" ");
        int length1 = s2.length;
        String s4 = byteToHex(length1);
        String s5 = s4 + " " + s;
        return s5;
    }



    public  String editLicense(String license) throws UnsupportedEncodingException {
        String head = "05";
        byte[] provinceByte = license.getBytes("gb2312");
        String s = BinaryToHexString(provinceByte);
        String[] s1 = s.split(" ");
        int length = s1.length;
        String s3 = byteToHex(length);
        s = head + " " + s3 + " " + s;
        String a = byteToHex(checkSum(s));
        s=s+a;
        String[] s2 = s.split(" ");
        int length1 = s2.length;
        String s4 = byteToHex(length1);
        String s5 = s4 + " " + s;
        return s5;
    }


    public  int checkSum(String s) {
        byte[] data = hexStringToByteArray(s);
        int sum = 0;
        for (byte b : data) {
            sum += b & 0xFF; // 将字节转换为无符号整数并相加
        }
        return ~sum & 0xFF; // 取反并只取低8位
    }





}

